package com.cxh.mchat.socket;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.cxh.mchat.bussiness.entity.Message;
import com.cxh.mchat.bussiness.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cxh
 * @date 2021/12/23 18:08
 **/
@ServerEndpoint(value="/ws/{sid}")
@Slf4j
@Component
public class DemoWebsocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName){
        sessionPools.put(userName, session);
        addOnlineCount();
        log.info(userName + "加入webSocket！当前人数为" + onlineNum);
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName){
        sessionPools.remove(userName);
        subOnlineCount();
        log.info(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String messageStr) throws IOException{
        log.info(messageStr);
        if(!StringUtils.hasText(messageStr)){
            log.warn("消息为空");
            return;
        }
        Message message = JSON.parseObject(messageStr, Message.class);
        if(null == message){
            log.warn("消息无法解析");
            return;
        }

        if(true){// 单聊和群聊
            String receivedUserNo = message.getReceivedUserNo();
            Session session = sessionPools.get(receivedUserNo);
            sendSingleMessage(session, message);
        }else {
            sendGroupMessage(message);
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("发生错误");
        throwable.printStackTrace();
    }

    //发送消息
    public void sendGroupMessage(Message message) throws IOException {
        for (Session session: sessionPools.values()) {
            sendSingleMessage(session, message);
        }
    }
    //给指定用户发送信息
    public void sendSingleMessage(Session session, Message message){
        if(null != session){
            try {
                session.getBasicRemote().sendText(message.getText());
            } catch (IOException e) {
                log.error("发送异常", e);
            }
        }
        IMessageService messageService = SpringUtil.getBean(IMessageService.class);
        messageService.add(message);
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
